<template>
  <div class="div-pop" v-if="isGetSkuBuy" @click="close" catchtouchmove>
    <div class="get-sku-buy" catchtap>
      <div class="flex border-b pos-rel">
        <div class="pad-t-15 pad-b-15 pad-r-8">
          <img :src="skuImage + '?imageView2/1/w/300/h/300'" mode="aspectFill" class="img-item"/>
        </div>
        <div class="close-btn" @click="close">
          <img v-if="fileSpace" mode="widthFix" class="width-19 height-19" :src="fileSpace + '/images/close-icon-2.png'"/>
        </div>
      </div>
      <div>
        <scroll-view scroll-y="" class="clearfix scroll-sky">
          <div v-for="(item, index) in skuPropList" :key="index" class="pad-t-8 pad-b-8">
            <div class="font-w font-15 pad-b-7">{{ item.skuPropName }}</div>
            <div class="flex flex-wrap">
              <label v-for="(skuPropValue, indexValue) in item.skuPropValueList" :key="indexValue">
                <div v-if="skuPropValue.showFlag !== 2"
                  class="sku-prop-value align-c" @click="selSkuPropValue(index, skuPropValue.skuPropValueId)"
                  :class="{'sel-prop-value' : skuPropValue.showFlag === 1, 'disable-prop-value' : skuPropValue.showFlag === 2}"                  
                  :key="indexValue">
                  {{ skuPropValue.skuPropValue }}
                </div>
                <div v-else
                  class="sku-prop-value align-c disable-prop-value"                  
                  :key="indexValue">
                  {{ skuPropValue.skuPropValue }}
                </div>
              </label>
            </div>
          </div>
        </scroll-view>
      </div>
      <div class="pad-t-8 pad-b-15 mar-b-10">
        <div class="font-w font-15 pad-b-12">购买数量</div>
        <div>
          <van-stepper v-model="goodsNum" @change="onChangeGoodsNum"/>
        </div>
      </div>
      <div class="confirm-btn">
        <div class="btn flex">
          <span v-if="!buyNowBoolean" class="flex-item" @click="save(true)">加入购物车</span>
          <span class="flex-item" :class="buyNowBoolean ? 'buy-now':''" @click="save(false)">立即购买</span>
        </div>
      </div>
      <div class="pad-10" v-if="isIPhoneX"></div>
    </div>
  </div>
</template>

<script>
  import {
    addShoppingCart
  } from '@/api/shop'

  export default {
    data() {
      return {
        goods: {
          skuPropList: [],
          skuList: [],
          values: []
        },
        skuPropList: [],
        skuList: [],
        values: [],
        isGetSkuBuy: false,
        isComponents: true,
        isCart: true,
        isStock: true,
        selSkuPropValueList: [],
        goodsNum: 1,
        skuPrice: 0,
        skuId: '',
        skuImage: '',
        comissionFlag: null,
        stockSkuNum: 0,
        qty: '',
        skuDetail: '',
        buyNowBoolean: false,
        SKUResult: {}
      }
    },
    props: {
      goodsType: {
        type: Number,
        default: 0
      },
      goodsData: {
        type: Object,
        default: {}
      },
      skuPropList: {
        type: Array,
        default: []
      },
      skuList: {
        type: Array,
        default: []
      },
      values: {
        type: Array,
        default: []
      },
      room_id: {
        type: String,
        default: ''
      }
    },
    computed: {
      isIPhoneX() {
        return this.$utils.isIPhoneX()
      }
    },
    onShow() {
      this.close()
    },
    methods: {
      getObjKeys(obj) {
        if (obj !== Object(obj)) {
          return
        }
        var keys = []
        for (var key in obj) {
          // var m = key
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
            // var n = key
            keys[keys.length] = key
          }
        }
        return keys
      },
      add2SKUResult(combArrItem, sku) {
        var key = combArrItem.join(',')
        key = this.arrangeKey(key)
        if (this.SKUResult[key]) { // SKU信息key属性·
          this.SKUResult[key].stock += sku.stock
        } else {
          this.SKUResult[key] = {
            stock: sku.stock,
            skuId: sku.skuId
          }
        }
      },
      arrangeKey(skuKey) {
        /* key由小到大排列*************************************/
        var skuKeyAttrs = skuKey.split(',') // SKU信息key属性值数组
        skuKeyAttrs.sort(function(value1, value2) {
          return parseInt(value1) - parseInt(value2)
        })
        skuKey = skuKeyAttrs[0]
        for (var m = 1; m < skuKeyAttrs.length; m++) {
          skuKey += ',' + skuKeyAttrs[m]
        }
        return skuKey
      },
      combInArray(aData) {
        if (!aData || !aData.length) {
          return []
        }
        var len = aData.length
        var aResult = []
        for (var n = 1; n < len; n++) {
          var aaFlags = this.getCombFlags(len, n)
          while (aaFlags.length) {
            var aFlag = aaFlags.shift()
            var aComb = []
            for (var i = 0; i < len; i++) {
              aFlag[i] && aComb.push(aData[i])
            }
            aResult.push(aComb)
          }
        }
        return aResult
      },
      getCombFlags(m, n) {
        if (!n || n < 1) {
          return []
        }
        var aResult = []
        var aFlag = []
        var bNext = true
        var i, j, iCnt1
        for (i = 0; i < m; i++) {
          aFlag[i] = i < n ? 1 : 0
        }
        aResult.push(aFlag.concat())
        while (bNext) {
          iCnt1 = 0
          for (i = 0; i < m - 1; i++) {
            if (aFlag[i] === 1 && aFlag[i + 1] === 0) {
              for (j = 0; j < i; j++) {
                aFlag[j] = j < iCnt1 ? 1 : 0
              }
              aFlag[i] = 0
              aFlag[i + 1] = 1
              var aTmp = aFlag.concat()
              aResult.push(aTmp)
              if (aTmp.slice(-n).join('').indexOf('0') === -1) {
                bNext = false
              }
              break
            }
            aFlag[i] === 1 && iCnt1++
          }
        }
        return aResult
      },
      show(goods, isCart, comissionFlag, qty, type) {
        // 初始化data
        Object.assign(this.$data, this.$options.data())
        this.selSkuPropValueList = []
        // this.goods = {}
        if (this.goodsData) {
          this.goods = this.goodsData
          this.qty = qty
          // 多规格
          if (this.skuPropList && this.skuList) {
            // this.skuPropList = this.goodsData.skuPropList
            // this.skuList = this.goodsData.skuList
            // this.values = this.goodsData.values
            // 初始化selSkuPropValueList
            this.skuPropList.forEach((itemDetop, indexDetop) => {
              itemDetop.skuPropValueList.forEach((itemDetopSub, indexDetopSub) => {
                itemDetopSub.showFlag = 0
              })
              if (!this.selSkuPropValueList[indexDetop]) {
                this.selSkuPropValueList.push({})
              }
            })
          }
        }
        if (type) {
          this.buyNowBoolean = true
        }
        this.isCart = isCart
        this.isGetSkuBuy = true
        this.comissionFlag = comissionFlag
        this.skuImage = this.goods.images[0]
      },
      close() {
        this.selSkuPropValueList = []
        this.goods = {}
        this.isGetSkuBuy = false
      },
      save(booleanVal) {
        this.isCart = booleanVal
        let roomId = this.room_id || ''
        console.log('save, shareMemberId: ' + this.goods.shareMemberId)
        if (!this.isFinishedSel()) return this.$utils.showToast({ title: '请选择商品规格' })
        if (!this.isStock) return this.$utils.showToast({ title: '您选择的商品，已售罄，请重新选择！' })
        if (this.goods.stock) {
          if (this.goodsNum > this.goods.stock) return this.$utils.showToast({ title: '您购买的商品数量，已超出库存，抱歉！' })
        }
        if (this.stockSkuNum) {
          if (this.goodsNum > this.stockSkuNum) return this.$utils.showToast({ title: '您购买的商品数量，已超出库存，抱歉！' })
        }
        let skuPropValueIds = []
        this.selSkuPropValueList.forEach((item) => {
          skuPropValueIds.push(item.skuPropValueId)
        })
        if (this.isCart) {
          const shoppingCart = {
            customerId: this.getCustomerId,
            goodsId: this.goods.goodsId,
            goodsNum: this.goodsNum,
            memberId: this.getMemberId,
            goodsType: this.goodsType,
            shoppingCartType: this.goodsType === 30 || this.goodsType === 31 || this.goodsType === 32 ? 3 : 1
          }
          if (!this.getShowBuyCard) {
            shoppingCart.customerId = this.getMemberId
          }
          if (this.goods.shareMemberId) {
            shoppingCart.shareMemberId = this.goods.shareMemberId
          }
          if (this.skuId) {
            shoppingCart.skuId = this.skuId
          }
          addShoppingCart(shoppingCart).then((response) => {
            if (response.isError) return
            this.$utils.showToast({ title: '已加入购物车', icon: 'success' })
            this.$emit('finished')
          }).catch(() => {
          })
        } else {
          console.log('我在sku选择器:', this.room_id)
          if (this.goods.shareMemberId) {
            console.log('$pt')
            this.$pt.navigateTo({
              url: '/pages/shop/buy/main?goodsId=' + this.goods.goodsId + '&skuId=' +
                this.skuId + '&goodsNum=' + this.goodsNum + '&goodsType=' + this.goodsType + '&shareMemberId=' + this.goods.shareMemberId +
                 '&comissionFlag=' + this.comissionFlag + '&room_id=' + roomId
            })
          } else {
            console.log('navigateTo')
            this.$pt.navigateTo({
              // featuresType 测试先写死
              url: `/pages/shop/buy/main?goodsId=${this.goods.goodsId}&skuId=${this.skuId}&goodsNum=${this.goodsNum}&goodsType=${this.goodsType}
              &comissionFlag=${this.comissionFlag}&room_id=${roomId}&featuresType=11`
              // url: '/pages/shop/buy/main?goodsId=' + this.goods.goodsId + '&skuId=' +
              //   this.skuId + '&goodsNum=' + this.goodsNum + '&goodsType=' + this.goodsType + '&comissionFlag=' + this.comissionFlag + '&room_id=' + roomId
            })
          }
        }
        this.close()
        this.isGetSkuBuy = false
      },
      selSkuPropValue(skuPropIndex, skuPropValueId) {
        // var data = {'小;白;高': {'count': 40}, '大;白;高': {'count': 20}, '小;黑;高': {'count': 0}, '大;黑;高': {'count': 10}}
        var i = null
        var j = null
        // console.log(this.values)
        var skuKeys = this.getObjKeys(this.values)
        // console.log('skuKeys')
        // console.log(skuKeys)
        for (i = 0; i < skuKeys.length; i++) {
          var skuKey = skuKeys[i] // 一条SKU信息key
          var sku = this.values[skuKey] // 一条SKU信息value
          var skuKeyAttrs = skuKey.split(',') // SKU信息key属性值数组
          skuKeyAttrs.sort(function(value1, value2) {
            return parseInt(value1) - parseInt(value2)
          })
          // 对每个SKU信息key属性值进行拆分组合
          var combArr = this.combInArray(skuKeyAttrs)
          for (j = 0; j < combArr.length; j++) {
            this.add2SKUResult(combArr[j], sku)
          }
          this.SKUResult[skuKeyAttrs.join(',')] = {
            stock: sku.stock,
            skuId: sku.skuId
          }
        }
        let dataList = []
        const colArr = ['subData', 'name']
        dataList = this.$utils.objToArr(this.SKUResult, colArr)
        // console.log(dataList)
        let showId = ''
        // 拷贝属性，使其更新
        this.selSkuPropValueList = Object.assign([], this.selSkuPropValueList)
        // console.log('this.selSkuPropValueList')
        // console.log(this.selSkuPropValueList) // 已选中数组
        this.skuPropList.forEach((item, index) => {
          if (!this.selSkuPropValueList[index]) {
            this.selSkuPropValueList.push({})
          }
          if (skuPropIndex === index) {
            let otherIdData = []
            // let skuIdData = []
            if (this.selSkuPropValueList[index].skuPropValueId === skuPropValueId) {
              item.skuPropValueList.forEach((itemSub, indexSub) => {
                itemSub.showFlag = 0
                otherIdData = []
                // skuIdData = []
              })
              this.selSkuPropValueList[index].skuPropValueId = ''
            } else {
              this.selSkuPropValueList[index].skuPropValueId = skuPropValueId
              // console.log('selSkuId')
              // console.log(this.selSkuPropValueList[index].skuPropValueId)
              item.skuPropValueList.forEach((itemSub, indexSub) => {
                otherIdData = []
                // skuIdData = []
                itemSub.showFlag = 0
                if (this.selSkuPropValueList[index].skuPropValueId === itemSub.skuPropValueId) {
                  showId = itemSub.skuPropValueId
                  itemSub.showFlag = 1
                  // sku展示库存为0的灰度展示
                  // itemSub.skuPropValueId 为 选中的valueId，在 skuPropList 里
                  this.skuPropList.forEach((itemOnTop, indexOnTop) => {
                    itemOnTop.skuPropValueList.forEach((itemOtherOnSub, indexOtherOnSub) => {
                      if (itemOtherOnSub.showFlag === 2) {
                        itemOtherOnSub.showFlag = 0
                      }
                    })
                  })
                  // console.log('itemData')
                  dataList.forEach((itemData, indexData) => {
                    let len = 0
                    if (itemData.name.indexOf(',') !== -1) {
                      len = (itemData.name.split(',')).length
                      itemData.len = len
                    } else {
                      itemData.len = 1
                    }
                    if (itemData.subData.stock === 0 && itemData.len === this.skuPropList.length) {
                      // console.log(itemData.name)
                      otherIdData.push(itemData.name.split(','))
                    }
                  })
                }
              })
            }
          }
        })
        // 已选中的数据处理
        let selDataArr = [] // 已选中数组
        let selDataStr = '' // 已选中字符串
        let stockNoneValueId = [] // 库存为空相关联的ID值
        this.selSkuPropValueList.forEach((item, index) => {
          if (item.skuPropValueId) {
            selDataArr.push(item.skuPropValueId)
          }
        })
        // console.log('selDataStr')
        selDataStr = selDataArr.join(',')
        // console.log(selDataStr)
        // console.log('item.name list')
        dataList.forEach((item, index) => {
          if (selDataStr !== item.name && item.name.indexOf(selDataStr) !== -1 && item.subData.stock === 0) {
            console.log(item.name)
            stockNoneValueId.push(item.name.split(','))
            stockNoneValueId = [].concat.apply([], stockNoneValueId)
          }
        })
        // console.log('stockNoneValueId')
        // console.log(stockNoneValueId)
        if (stockNoneValueId.length === 0) {
          this.skuPropList.forEach((itemProp, indexProp) => {
            itemProp.skuPropValueList.forEach((itemPropSub, indexPropSub) => {
              if (itemPropSub.showFlag === 1) {
                itemPropSub.showFlag = 1
              }
              if (itemPropSub.showFlag === 2) {
                itemPropSub.showFlag = 0
              }
            })
          })
          selDataArr.forEach((itemArr, indexArr) => {
            this.skuPropList.forEach((itemProp, indexProp) => {
              itemProp.skuPropValueList.forEach((itemPropSub, indexPropSub) => {
                if (itemPropSub.skuPropValueId === itemArr) {
                  itemPropSub.showFlag = 1
                }
              })
            })
          })
        } else {
          // 设置库存不足，设置不可选择
          stockNoneValueId.forEach((itemSelData, indexSel) => {
            this.skuPropList.forEach((itemProp, indexProp) => {
              itemProp.skuPropValueList.forEach((itemPropSub, indexPropSub) => {
                if (itemSelData === itemPropSub.skuPropValueId) {
                  itemPropSub.showFlag = 2
                }
              })
            })
          })
          // 已选中的规格，设置选中
          if (selDataArr.length === 0) {
            this.skuPropList.forEach((itemProp, indexProp) => {
              itemProp.skuPropValueList.forEach((itemPropSub, indexPropSub) => {
                itemPropSub.showFlag = 0
                this.skuDetail = ''
                this.skuPrice = this.goods.price
                this.stockSkuNum = this.goods.stock
                this.skuImage = this.goods.images[0]
              })
            })
          } else {
            selDataArr.forEach((itemSelData, indexSel) => {
              this.skuPropList.forEach((itemProp, indexProp) => {
                itemProp.skuPropValueList.forEach((itemPropSub, indexPropSub) => {
                  if (itemSelData === itemPropSub.skuPropValueId) {
                    itemPropSub.showFlag = 1
                  }
                })
              })
            })
          }
        }
        // 读取sku价格
        if (this.isFinishedSel()) {
          this.skuList.forEach((item) => {
            let isGetSkuPrice = true
            item.skuDetailList.forEach((skuDetail, index) => {
              if (skuDetail.skuPropValueId !== this.selSkuPropValueList[index].skuPropValueId) {
                isGetSkuPrice = false
              }
            })
            if (isGetSkuPrice) {
              this.skuPrice = item.price
              this.skuId = item.skuId
              this.stockSkuNum = item.stock
              let arrDetail = item.skuDetail.split(';')
              this.skuDetail = arrDetail.join(' ')
              if (item.imageUrl) {
                this.skuImage = item.imageUrl
              }
              // console.log('select true')
              // console.log(item)
              this.skuPropList.forEach((itemList, index) => {
                itemList.skuPropValueList.forEach((itemSub, indexSub) => {
                  if (this.selSkuPropValueList[index].skuPropValueId === itemSub.skuPropValueId) {
                    itemSub.showFlag = 1
                  }
                })
              })
              if (item.stock === 0) {
                // console.log('showId')
                // console.log(showId)
                this.skuPropList.forEach((itemList, index) => {
                  itemList.skuPropValueList.forEach((itemSub, indexSub) => {
                    if (itemSub.showFlag === 1) {
                      itemSub.showFlag = 2
                    }
                    if (showId === itemSub.skuPropValueId) {
                      itemSub.showFlag = 1
                    }
                  })
                })
                this.stockSkuNum = '0'
                this.isStock = false
                // this.$utils.showToast({ title: '您选择的商品，已售罄，请重新选择！' })
              } else {
                this.isStock = true
              }
            }
          })
        }
      },
      // 是否完成了选择规格
      isFinishedSel() {
        let isDone = true
        this.selSkuPropValueList.forEach((item) => {
          // console.log('item.skuPropValueId')
          // console.log(item.skuPropValueId)
          if (!item.skuPropValueId) {
            isDone = false
            return isDone
          }
        })
        return isDone
      },
      onChangeGoodsNum(e) {
        console.log(e)
        this.goodsNum = e.mp.detail
      }
    }
  }
</script>

<style lang="less" scoped>
.get-sku-buy {
  width: 375px;
  box-sizing: border-box;
  padding: 0 20px;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 990;
  .close-btn {
    position: absolute;
    width: 36px;
    height: 36px;
    right: -8px;
    top: 9px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .border-b {
    border-bottom: #f7f7f7 1px solid;
  }
  .scroll-sky {
    max-height: 275px;
  }
  .stock-num {
    font-size: 12px;
    padding-top: 24px;
    color: #949494;
  }
  .sku-detail {
    font-size: 12px;
    padding-top: 1px;
    color: #949494;
  }
}

.img-item {
  width: 100px;
  height: 100px;
}

.goods-title {
  height: 50px;
  overflow: hidden;
}

.confirm-btn {
  color: #fff;
  padding: 10px 0;
  text-align: center;
  .btn {
    overflow: hidden;
    border-radius: 100px;
    .flex-item {
      display: inline-block;
      height: 42px;
      line-height: 42px;
      font-size: 15px;
      color: #333333;
      background: #ffe200;
      cursor: pointer;
      .self-shop {
        font-size: 8px;
        span {
          color: #ff001d;
        }
      }
      &.buy-now {
        color: #333333 !important;
        background: #ffe200 !important;
      }
      &:last-child {
        line-height: unset;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
      &:first-child {
        background: #333333;
        color: #fff;
      }
    }
  }
}

.sku-prop-value {
  background-color: #f2f2f2;
  padding: 4px 13px;
  border-radius: 100px;
  margin-right: 15px;
  margin-top: 5px;
  min-width: 30px;
  color: #333333;
}

.sel-prop-value {
  background-color: #ffd005;
}
.disable-prop-value {
  color: #d2d2d2;
  background-color: #f7f7f7;
}
.line-h-1 {
  line-height: 1;
}
</style>
